﻿using System;
using System.ComponentModel;

namespace Deeper.Common
{
	public static class TypeChange
	{
		/// <summary>
		/// 类型转换
		/// </summary>
		/// <param name="value"></param>
		/// <param name="conversionType"></param>
		/// <returns></returns>
		private static object Change(object value, Type conversionType)
		{
			if (conversionType.IsNull())
				throw new ArgumentNullException("被转换类型不能为空");

			if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
			{
				if (value == null) return null;
				NullableConverter nullableConverter = new NullableConverter(conversionType);
				conversionType = nullableConverter.UnderlyingType;
			}
			return Convert.ChangeType(value, conversionType);
		}

		/// <summary>
		/// 数据类型转换
		/// </summary>
		/// <param name="value"></param>
		/// <param name="type"></param>
		/// <returns></returns>
		public static object ChangeType(this object value, Type type)
		{
			if (value == null && type.IsGenericType) return Activator.CreateInstance(type);
			if (value == null) return null;
			if (type == value.GetType()) return value;
			if (type.IsEnum)
			{
				if (value is string)
					return Enum.Parse(type, value as string);
				return Enum.ToObject(type, value);
			}
			if (!type.IsInterface && type.IsGenericType)
			{
				Type innerType = type.GetGenericArguments()[0];
				object innerValue = Change(value, innerType);
				return Activator.CreateInstance(type, new[] { innerValue });
			}
			if (value is string && type == typeof(Guid)) return new Guid(value as string);
			if (value is string && type == typeof(Version)) return new Version(value as string);
			if (!(value is IConvertible)) return value;
			return Convert.ChangeType(value, type);
		}

	}



}
